<template>
	<view class="goods-container">
		<!-- 全屏加载状态 -->
		<view class="full-screen-loading" v-if="loading">
			<u-loading size="36" mode="circle"></u-loading>
			<text class="loading-text">加载中...</text>
		</view>
		
		<template v-else>
			<!-- 顶部筛选/搜索栏 -->
			<view class="filter-bar">
				<view class="category-filter" @click="showCategoryPicker = true">
					<text>{{ selectedCategory.categoryName }}</text>
					<u-icon name="arrow-down-fill" size="10" color="#8c8c8c"></u-icon>
				</view>
				<view class="search-input">
					<u-search placeholder="输入货品名称/条形码查找" v-model="keyword" :show-action="false" height="64"
						search-icon-color="#bfbfbf" placeholder-color="#bfbfbf" bg-color="#fff" shape="square"
						:clearabled="true" @search="handleSearch" @custom="handleSearch"></u-search>
				</view>
				<view class="add-button" @click="addGoods">
					<u-icon name="plus" size="24" color="#595959"></u-icon>
				</view>
			</view>

			<!-- 货品列表 -->
			<view class="goods-list">
				
				<template v-if="goodsList.length !== 0">
					<view class="goods-item" v-for="(item, index) in goodsList" :key="item && (item.id || index)"
						@click="item && viewGoodsDetail(item)">
						<view class="goods-image">
							<u-image :src="(item && item.goodsImage) || defaultImage" width="120rpx" height="120rpx"
								mode="aspectFit" radius="4"></u-image>
						</view>
						<view class="goods-info">
							<text class="name">{{ item && (item.goodsSpec || '未命名商品') }}</text>
							<view class="price-row">
								<text class="label">批发1:</text>
								<text class="price">¥{{ formatPrice(item && item.wholesalePrice1) }}</text>
								<text class="label" style="margin-left: 30rpx;">批发2:</text>
								<text class="price">¥{{ formatPrice(item && item.wholesalePrice2) }}</text>
								<text class="label" style="margin-left: 30rpx;">进货:</text>
								<text class="price">¥{{ formatPrice(item && item.purchasePrice) }}</text>
							</view>
							<view class="price-row">
								<text class="label">零售:</text>
								<text class="price">¥{{ formatPrice(item && item.retailPrice) }}</text>
								<text class="label" style="margin-left: 30rpx;">库存:</text>
								<text class="stock">{{ item && (item.stock || item.stockQuantity || 0) }}</text>
							</view>
						</view>
					</view>
				</template>

				<view v-else class="empty-list">
					<u-empty mode="list" text="暂无货品"></u-empty>
				</view>

				<!-- 加载状态 -->
				<view class="loading-status" v-if="goodsList.length > 0">
					<view v-if="loadingMore" class="loading">
						<u-loading size="24" mode="circle"></u-loading>
						<text>加载中...</text>
					</view>
					<view v-else-if="finished" class="finished">
						<text>—— 已加载全部数据 ——</text>
					</view>
				</view>
			</view>

			<u-picker :show="showCategoryPicker" :columns="categoryColumns" keyName="label" @confirm="confirmCategory"
				@cancel="showCategoryPicker = false"></u-picker>
		</template>
	</view>
</template>

<script>
	import api from '@/utils/api.js'
	import {
		url
	} from '../../constant/domain';

	export default {
		data() {
			return {
				selectedCategory: {
					categoryName: '全部类别',
					id: null
				},
				showCategoryPicker: false,
				categoryColumns: [
					// 初始分类数据
					[{
						categoryName: '全部类别',
						id: null
					}]
				],
				keyword: '',
				defaultImage: '/static/images/default-goods.png', // 默认商品图片路径
				goodsList: [], // 初始为空数组，通过API获取数据
				totalStock: 0, // 新增 totalStock 数据
				// 分页相关
				pageNum: 1,
				pageSize: 10,
				totalPage: 1,
				loading: false,
				refreshing: false,
				loadingMore: false,
				finished: false,
				needRefresh: true, // 标记是否需要刷新数据
			};
		},
		methods: {
			// 加载分类数据
			loadCategories() {
				api.getCategoryList().then(res => {
					console.log('原始分类数据:', res);

					// 处理扁平结构的分类数据
					if (res && Array.isArray(res)) {
						// 先将所有分类转为{id -> 分类}的映射
						const categoryMap = {};
						res.forEach(item => {
							// 深拷贝，确保不修改原始数据
							categoryMap[item.id] = {
								...item,
								children: []
							};
						});

						// 根节点列表
						const rootCategories = [];

						// 构建树形结构
						res.forEach(item => {
							// 如果有父节点且父节点存在于映射中
							if (item.parentId && item.parentId !== 0 && categoryMap[item.parentId]) {
								// 将当前节点添加到父节点的children中
								categoryMap[item.parentId].children.push(categoryMap[item.id]);
							} else {
								// 没有父节点或父节点不存在，作为根节点
								rootCategories.push(categoryMap[item.id]);
							}
						});

						console.log('构建的树形结构:', rootCategories);

						// 将树形结构扁平化，用于选择器显示
						const flattenCategories = this.flattenCategoryTree(rootCategories);
						console.log('扁平化后的分类:', flattenCategories);

						// 确保全部类别在最前面
						this.categoryColumns = [flattenCategories];

						// 设置默认选中的分类
						if (flattenCategories.length > 0) {
							this.selectedCategory = flattenCategories[0];
						}
					}
				}).catch(err => {
					console.error('加载分类数据失败:', err);
					uni.showToast({
						title: '加载分类数据失败',
						icon: 'none'
					});
				});
			},

			// 将树形结构扁平化
			flattenCategoryTree(tree) {
				if (!tree || !Array.isArray(tree) || tree.length === 0) {
					console.log('分类树为空');
					return [];
				}

				console.log('开始扁平化分类树，节点数:', tree.length);
				let result = [];

				// 递归处理树形结构
				const process = (items, level = 0) => {
					if (!items || !Array.isArray(items) || items.length === 0) return;

					items.forEach(item => {
						// 跳过无效数据
						if (!item || !item.categoryName) {
							console.log('跳过无效分类项', item);
							return;
						}

						// 添加当前节点（添加层级标识）
						const prefix = level > 0 ? '　'.repeat(level) + '└ ' : '';
						const categoryName = prefix + item.categoryName;

						console.log(`添加分类[L${level}]:`, categoryName);

						result.push({
							...item,
							label: categoryName, // 添加label属性供选择器使用
							categoryName: categoryName
						});

						// 处理子节点
						if (item.children && Array.isArray(item.children) && item.children.length > 0) {
							process(item.children, level + 1);
						}
					});
				};

				process(tree);
				console.log('扁平化分类完成，共', result.length, '个分类');
				return result;
			},

			confirmCategory(e) {
				console.log('选择分类:', e);

				// 获取选择的分类
				const selected = e.value[0];

				if (selected) {
					// 更新选中的分类
					this.selectedCategory = {
						id: selected.id,
						categoryName: selected.categoryName
					};

					// 关闭选择器
					this.showCategoryPicker = false;

					console.log('已选择分类:', this.selectedCategory);

					// 根据选择的分类ID重新获取货品列表
					this.pageNum = 1; // 重置页码
					this.fetchGoodsList();
				} else {
					uni.showToast({
						title: '选择分类失败',
						icon: 'none'
					});
				}
			},
			handleSearch() {
				// 根据 keyword 重新获取或过滤货品列表
				console.log('Search keyword:', this.keyword);
				this.fetchGoodsList();
			},
			addGoods() {
				// 跳转到添加货品页面
				uni.navigateTo({
					url: '/pages/goods/add'
				}); // 假设添加页面路径
			},
			viewGoodsDetail(item) {
				console.log('点击商品项', item);

				// 检查item是否存在
				if (!item) {
					console.error('商品数据为空');
					uni.showToast({
						title: '商品数据错误',
						icon: 'none'
					});
					return;
				}

				// 确定商品ID
				const goodsId = item.id || item.goodsId;

				console.log('商品ID:', goodsId);

				if (!goodsId) {
					console.error('商品ID不存在:', item);
					uni.showToast({
						title: '商品ID不存在',
						icon: 'none'
					});
					return;
				}

				console.log('跳转商品详情，ID:', goodsId);

				// 使用setTimeout确保不会频繁点击
				setTimeout(() => {
					uni.navigateTo({
						url: `/pages/goods/detail?id=${goodsId}`,
						fail: (err) => {
							console.error('跳转失败:', err);
							uni.showToast({
								title: '页面跳转失败',
								icon: 'none'
							});
						}
					});
				}, 100);
			},
			fetchGoodsList(isLoadMore = false) {
				this.loading = true;

				if (isLoadMore) {
					this.loadingMore = true;
				} else {
					// 如果是下拉刷新或第一次加载，重置页码和数据
					this.pageNum = 1;
					this.goodsList = [];
					this.finished = false;
				}

				// 如果已加载全部页面，则不再请求
				if (isLoadMore && this.pageNum >= this.totalPage) {
					console.log('已加载全部数据');
					this.loading = false;
					this.loadingMore = false;
					this.finished = true;
					return;
				}

				const params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					goodsSpec: this.keyword && this.keyword.trim() ? this.keyword.trim() : ''
				};

				// 只有在选择了特定分类时才添加categoryId参数
				if (this.selectedCategory && this.selectedCategory.id !== null) {
					params.goodsCategoryId = this.selectedCategory.id;
				}

				console.log('商品查询参数:', params);



				api.getGoodsList(params).then(response => {
					console.log('API返回数据:', response);

					// 处理分页数据结构
					if (response && response.rows && Array.isArray(response.rows)) {
						// 过滤无效数据
						const validRows = response.rows.filter(item => item && typeof item === 'object');

						// 确保每个商品都有id
						const processedRows = validRows.map((item, index) => {
							// 如果没有id，使用其他可能的id字段或生成临时id
							if (!item.id) {
								const tempId = item.goodsId || item.productId || `temp-id-${index}`;
								return {
									...item,
									id: tempId
								};
							}
							return item;
						});

						// 合并数据
						if (isLoadMore) {
							this.goodsList = [...this.goodsList, ...processedRows];
						} else {
							this.goodsList = processedRows;
						}

						// 更新分页信息
						this.totalCount = response.total || 0;
						this.totalPage = response.totalPage || Math.ceil(this.totalCount / this.pageSize) || 1;

						// 检查是否已加载完所有数据
						this.finished = this.pageNum >= this.totalPage;

						console.log('商品列表加载成功', this.goodsList.length, '总数:', this.totalCount, '总页数:', this
							.totalPage);
					} else {
						if (!isLoadMore) {
							this.goodsList = [];
						}
						this.finished = true;
						console.error('商品列表数据格式异常:', response);
					}
				}).catch(err => {
					console.error('获取商品列表失败:', err);
					uni.showToast({
						title: '获取商品列表失败',
						icon: 'none'
					});
					this.finished = true;
				}).finally(() => {
					this.loading = false;
					this.loadingMore = false;
					uni.stopPullDownRefresh();
				});
			},
			formatPrice(price) {
				if (price === undefined || price === null || price === '') return '0.00';
				const num = Number(price);
				return isNaN(num) ? '0.00' : num.toFixed(2);
			},
			// 加载更多
			loadMore() {
				if (this.loading || this.finished) return;

				// 页码+1
				this.pageNum++;

				console.log('加载更多，当前页码:', this.pageNum);

				// 加载更多数据
				this.fetchGoodsList(true);
			},

			// 下拉刷新
			onRefresh() {
				if (this.refreshing) return;
				this.refreshing = true;
				this.fetchGoodsList();
			}
		},
		onShow() {
			console.log('商品列表页面加载');
			
			// 如果需要刷新数据
			if (this.needRefresh) {
				// 立即将页面设置为加载状态，隐藏旧数据
				this.loading = true;

				// 先加载分类数据
				this.loadCategories();

				// 延迟200ms加载商品列表，确保分类数据已加载完成
				setTimeout(() => {
					this.fetchGoodsList();
					this.needRefresh = false; // 重置刷新标志
				}, 200);
			}
		},

		// 下拉刷新
		onPullDownRefresh() {
			this.onRefresh();
			uni.stopPullDownRefresh();
		},

		// 触底加载
		onReachBottom() {
			this.loadMore();
		},

		onHide() {
			this.needRefresh = true;
		}
	};
</script>

<style lang="scss" scoped>
	.goods-container {
		background-color: #f0f2f5;
		min-height: 100vh;
		padding-bottom: 100rpx; // 留出底部统计信息空间，如果统计信息需要固定在底部则需要改为 fixed 定位
	}

	.filter-bar {
		display: flex;
		align-items: center;
		padding: 15rpx 20rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #e8e8e8;
		gap: 15rpx;

		.category-filter {
			display: flex;
			align-items: center;
			background-color: #f0f2f5; // 类别按钮背景色
			padding: 10rpx 20rpx;
			border-radius: 30rpx;
			font-size: 26rpx;
			color: #595959;
			white-space: nowrap;

			.u-icon {
				margin-left: 8rpx;
			}
		}

		.search-input {
			flex: 1;

			/deep/ .u-search {
				padding: 0 !important; // 移除 u-search 可能的内边距
			}

			/deep/ .u-search__content {
				border-radius: 30rpx !important; // 输入框圆角
				height: 64rpx !important;
			}

			/deep/ .u-search__content__input {
				font-size: 26rpx !important;
			}
		}

		.add-button {
			padding: 10rpx;

			.u-icon {
				font-weight: bold;
			}
		}
	}

	.goods-list {
		margin-top: 16rpx;

		.empty-list {
			padding-top: 100rpx;
		}

		.goods-item {
			display: flex;
			background-color: #fff;
			padding: 25rpx 20rpx;
			border-bottom: 1rpx solid #f0f0f0;
			gap: 20rpx;
			align-items: flex-start; // 顶部对齐

			&:last-child {
				border-bottom: none;
			}

			.goods-image {
				flex-shrink: 0;
				background-color: #f7f8fa; // 图片占位背景
				border-radius: 8rpx;
				overflow: hidden;
				display: flex; // 使图片居中（如果图片比容器小）
				align-items: center;
				justify-content: center;

				/deep/ image {
					max-width: 100%; // 确保图片不超出容器
					max-height: 100%;
				}

				// 如果是 u-image, radius 属性会处理圆角
			}

			.goods-info {
				flex: 1;
				display: flex;
				flex-direction: column;
				gap: 8rpx; // 信息行间距

				.name {
					font-size: 30rpx;
					color: #303133;
					font-weight: 500;
					// 最多显示两行
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					margin-bottom: 5rpx;
				}

				.price-row {
					display: flex;
					align-items: center;
					font-size: 24rpx;

					.label {
						color: #8c8c8c;
						width: 70rpx; // 固定标签宽度
						flex-shrink: 0;
					}

					.price {
						color: #fa3534; // 价格颜色
						font-weight: 500;
						margin-right: 10rpx;
					}

					.stock {
						color: #595959;
					}
				}
			}
		}
	}

	.footer-summary {
		position: fixed; // 或者使用 padding-bottom 占位
		bottom: 0; // 如果是 fixed 定位
		left: 0;
		right: 0;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background-color: #fff;
		border-top: 1rpx solid #e8e8e8;
		font-size: 26rpx;
		color: #8c8c8c;
		// 如果使用 fixed 定位，需要同时调整 .goods-container 的 padding-bottom
		padding-bottom: constant(safe-area-inset-bottom);
		/* 兼容 iOS < 11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容 iOS >= 11.2 */
	}

	.loading-status {
		text-align: center;
		padding: 20rpx;

		.loading,
		.finished {
			margin-top: 10rpx;
		}
	}
	
	.loading-center {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding-top: 120rpx;
		
		.loading-text {
			margin-top: 20rpx;
			font-size: 26rpx;
			color: #909399;
		}
	}

	.full-screen-loading {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #f0f2f5;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		z-index: 999;
		
		.loading-text {
			margin-top: 20rpx;
			font-size: 28rpx;
			color: #909399;
		}
	}
</style>